package GUILayer;

import java.awt.BorderLayout;

import ControlLayer.DiscountGroupCtr;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;
import ModelLayer.DiscountGroup;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

public class DiscountGUI extends JPanel {

	private static final long serialVersionUID = 1L;
	private DefaultTableModel tableModel;
	private JTable table;
	private JScrollPane tableScrollPane;
	private JPanel tablePanel;

	private JTextField textField_Id;
	private JTextField textField_discount;
	private JTextField textField_Search;
	private JTextField textField_name;

	private DiscountGroupCtr dgCtr;

	public DiscountGUI() {
		dgCtr = new DiscountGroupCtr();
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());

		tablePanel = new JPanel();
		this.add(tablePanel, BorderLayout.CENTER);
		tablePanel.setLayout(new BorderLayout());
		JPanel searchPanel = new JPanel();
		textField_Search = new JTextField();

		textField_Search.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				showTable();
			}
		});

		textField_Search.setColumns(85);
		textField_name = new JTextField();
		searchPanel.add(textField_Search);
		tablePanel.add(searchPanel, BorderLayout.NORTH);

		GroupLayout gl_searchPanel = new GroupLayout(searchPanel);
		gl_searchPanel.setHorizontalGroup(gl_searchPanel.createParallelGroup(
				Alignment.LEADING).addComponent(textField_Search));
		gl_searchPanel.setVerticalGroup(gl_searchPanel.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_searchPanel
						.createSequentialGroup()
						.addGap(5)
						.addComponent(textField_Search,
								GroupLayout.PREFERRED_SIZE,
								GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)));
		searchPanel.setLayout(gl_searchPanel);

		addTable();

		JPanel groupPanel = new JPanel();
		this.add(groupPanel, BorderLayout.EAST);
		groupPanel.setLayout(new BoxLayout(groupPanel, BoxLayout.Y_AXIS));
		JPanel infoPanel = new JPanel();
		groupPanel.add(infoPanel);

		GroupLayout gl = new GroupLayout(infoPanel);
		infoPanel.setLayout(gl);
		infoPanel.setBorder(BorderFactory.createTitledBorder("Discount Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		JLabel lblId = new JLabel("Id: ");
		JLabel lblname = new JLabel("Name: ");
		JLabel lbldiscount = new JLabel("Discount: ");

		textField_Id = new JTextField();
		textField_discount = new JTextField();
		textField_Id.setColumns(40);
		textField_discount.setColumns(40);
		textField_Id.setEditable(false);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblId).addComponent(lblname)
								.addComponent(lbldiscount))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_Id)
								.addComponent(textField_name)
								.addComponent(textField_discount)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblId).addComponent(textField_Id))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblname)
								.addComponent(textField_name))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbldiscount)
								.addComponent(textField_discount)));

		JPanel panel = new JPanel();
		groupPanel.add(panel);
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JButton btnCreate = new JButton("Create");
		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!textField_Id.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please clear fields before creating new one",
							"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						dgCtr.createDg(textField_name.getText(), Double
								.parseDouble(textField_discount.getText()));
						JOptionPane.showMessageDialog(null,
								"The discount group is created",
								"Create Discountgroup",
								JOptionPane.INFORMATION_MESSAGE);
						cleanTextField();
						showTable();
					} catch (Exception a) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});
		panel.add(btnCreate);

		JButton btnSave = new JButton("Save");
		panel.add(btnSave);
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_Id.getText().isEmpty()) {
					JOptionPane
							.showMessageDialog(
									null,
									"Please select a discount group before saving editing information",
									"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						dgCtr.updateDg(
								Integer.parseInt(textField_Id.getText()),
								textField_name.getText(), Double
										.parseDouble(textField_discount
												.getText()));
						JOptionPane.showMessageDialog(null,
								"The discount group info is saved",
								"Update Discountgroup",
								JOptionPane.INFORMATION_MESSAGE);
						cleanTextField();
						showTable();
					} catch (Exception a) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});

		JButton btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_Id.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please select a discount group", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					int reply = JOptionPane.showConfirmDialog(null,
							"Do you want to delete this discount?",
							"Delete Discount", JOptionPane.YES_NO_OPTION,
							JOptionPane.WARNING_MESSAGE);
					if (reply == JOptionPane.YES_OPTION) {
						try {
							if (dgCtr.deleteDg(Integer.parseInt(textField_Id
									.getText())) == -1)
								JOptionPane
										.showMessageDialog(
												null,
												"Fail to delete discount group, because it associated with other objects",
												"Error",
												JOptionPane.ERROR_MESSAGE);
							JOptionPane.showMessageDialog(null,
									"The discount group is deleted",
									"Delete Discountgroup",
									JOptionPane.INFORMATION_MESSAGE);
							cleanTextField();
							showTable();
						} catch (Exception c) {
							JOptionPane.showMessageDialog(null,
									"Fail to delete discount", "Error",
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			}
		});
		panel.add(btnDelete);

		JButton btnCancel = new JButton("Clear");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
			}
		});
		panel.add(btnCancel);

		showTable();
	}

	public void cleanTextField() {
		textField_Id.setText("");
		textField_Search.setText("");
		textField_discount.setText("");
		textField_name.setText("");

	}

	public void addTable() {
		tableModel = new DefaultTableModel();
		tableModel.addColumn("Id");
		tableModel.addColumn("Name");
		tableModel.addColumn("Discount");

		tableScrollPane = new JScrollPane();
		table = new JTable(tableModel);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		table.setAutoCreateRowSorter(true);

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int row = table.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 1) {
					showDiscount(Integer.valueOf((Integer) table.getValueAt(
							row, 0)));

				}
			}
		});

		tablePanel.add(tableScrollPane, BorderLayout.CENTER);
		tableScrollPane.setViewportView(table);
	}

	public void showTable() {
		tableModel.setRowCount(0);
		String searchFilter = textField_Search.getText();

		ArrayList<DiscountGroup> dgs = dgCtr.getAllDg();
		for (DiscountGroup dg : dgs) {
			if (((Integer) dg.getId()).toString().toLowerCase()
					.contains(searchFilter.toLowerCase())
					|| dg.getName().toLowerCase()
							.contains(searchFilter.toLowerCase())) {
				tableModel.addRow(new Object[] { dg.getId(), dg.getName(),
						dg.getDiscount() });
			}
		}
	}

	public void showDiscount(int id) {
		try {
			DiscountGroup dg = dgCtr.getGroup(id);
			textField_Id.setText(Integer.toString(id));
			textField_discount.setText(Double.toString(dg.getDiscount()));
			textField_name.setText(dg.getName());
		} catch (Exception e) {

		}
	}

}
